<template>
  <div>
    <template v-for="item in menuList" :key="item.path">
      <!-- 有children时使用子菜单 -->
      <a-sub-menu :key="item.path" v-if="item.children && item.children.length">
        <template #title>
          <span @click="handleNav(item.path)">
            <component :is="item.icon"></component>
            <span>{{ item.title }}</span>
          </span>
        </template>
        <!-- 递归渲染子菜单时传递父路径 -->
        <Menu :menuList="item.children" :parent-path="getFullPath(item.path)" />
      </a-sub-menu>

      <!-- 无children时使用菜单项 -->
      <a-menu-item :key="item.path + ''" v-else @click="handleNav(item.path)">
        <component :is="item.icon"></component>
        <span>{{ item.title }}</span>
      </a-menu-item>
    </template>
  </div>
</template>

<script setup>
import { ref, defineProps, computed } from "vue";
import { useRouter } from "vue-router";
import Menu from "./Menu.vue";
const router = useRouter();
const props = defineProps({
  menuList: {
    type: Array,
    required: true,
  },
  parentPath: {
    type: String,
    default: "",
  },
});

// 计算完整路径
const getFullPath = computed(() => (path) => {
  if (!path) return "";
  return props.parentPath ? `${props.parentPath}/${path}` : `/${path}`;
});

//路由跳转
const handleNav = (path) => {
  // console.log(path);
  router.push({
    path: getFullPath.value(path),
  });
};
</script>
